package com.itheima.controller;/*
 *      .--,       .--,
 *     ( (  \.---./  ) )
 *     '.__/o   o\__.'
 *        {=  ^  =}
 *         >  -  <
 *        /       \
 *       //       \\
 *      //|   .   |\\
 *      "'\       /'"_.-~^`'-.
 *         \  _  /--'         `
 *       ___)( )(___
 *      (((__) (__)))    高山仰止,景行行止.虽不能至,心向往之。
 *
 * @author JiaoDaoNiu
 * @create 2022-09-24-16:02
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    //定义
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 增加菜品，包含口味。
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }



    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器对象
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();


        //条件构造器
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name!=null,Dish::getName,name);
        //添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,lqw);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        //用一个新的DishDto集合对象去接收每一个被赋值菜品分类名字的元素
        List<DishDto> list=records.stream().map((temp)->{
            //new一个新的DishDto对象去复制获取到每一个records集合里的元素的属性
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(temp,dishDto);

            //获元素也就是每个菜品中的分类Id
            Long categoryId = temp.getCategoryId();
            //根据获取到的id调dishService的方法获取dish对象
            Category category = categoryService.getById(categoryId);

            //可能初始数据有问题为null，故排除
            if(category!=null) {
                //得到了每一个菜品的所属此元素的菜品名字
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //返回dishDto对象
            return  dishDto;
        }).collect(Collectors.toList());

        //如此，把之前排除的Records值重新附上，并准备返回
        dishDtoPage.setRecords(list);
        //返回
        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable  Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("更新菜品");
        dishService.updateWithFlavor(dishDto);
        return R.success("菜品更新成功");
    }



    @PostMapping("/status/{s}")
    public R<String> updateToStatus(@PathVariable int s,@RequestParam List<Long> ids){
        log.info(ids.toString());
//        dishService.updateBatchById(ids);
        //根据对象才能底层封装修改所需修改的数据
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(s);
            dishService.updateById(dish);
        }

        if(s==0){
            return R.success("已停售");
        }
        return R.success("已启售");
    }

/*    *//**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     *//*
    @GetMapping("/list")
    public R<List<Dish>> listCategory(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();

        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        lqw.eq(Dish::getStatus,1);

        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lqw);


        return R.success(list);
    }*/

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }


    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        //调用service层，根据id删除
        dishService.removeDishWithDishFlavor(ids);
        return R.success("删除成功");

    }

}
